package it.struts.helloworld.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javassist.bytecode.Descriptor.Iterator;

/*
 * class to add items ,remove items and edit items in the shopping cart 
 * 
 */
public class Carrello implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 7967092814909724737L;
	protected int total;
	protected List<Prodotti> items;
	
	public Carrello()
		{
			items = new ArrayList<Prodotti>();
			total = 0;
		}

		//	 Add a new item and update the total
		public void addItem(Prodotti newItem)
		{
			//See if there's already an item like this in the cart
			boolean currIndex = items.isEmpty();	
			if (currIndex) {
				//If the item is new, add it to the cart
				items.add(newItem);
			} else {
				Boolean itemExists=false;
				for (java.util.Iterator<Prodotti> it =items.iterator(); it.hasNext (); ) {
				    Object o = it.next ();
				    Prodotti shop=(Prodotti)o;
				    if(shop.getProd_id() == newItem.getProd_id()){
				    	//update
				    	shop.update(newItem.getProd_id(), newItem.getNome(), newItem.getDescrizione(), newItem.getQuantita(), newItem.getPrezzo(), newItem.getStato());
				    	itemExists=true;
				    }
				  }
				if(!itemExists)
					items.add(newItem);

				
			}
		}
	

	public void removeItem(int itemCode) {
		//Find item
		for(int i=0; i<items.size();i++ ) {
			    Object o = items.get(i);
			    Prodotti shop=(Prodotti)o;
			    if(shop.getProd_id()==itemCode){	
			    	//Remove item
			    	items.remove(i);
			    	break;
			    }  
		}
		
	}

	public List getItems() {	
		return items;	
	}
	
	

}

